package logic

import (
	"context"
	"mall/mallrpc/mallrpc"
	"mall/pkg"
	"strconv"

	"mall/api/internal/svc"
	"mall/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	login, err := l.svcCtx.MallRpc.UserLogin(l.ctx, &mallrpc.UserLoginRequest{
		Tel:      req.Tel,
		Password: req.Password,
		Code:     req.Code,
	})
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    "500",
			Data:    nil,
		}, nil
	}
	handler, err := pkg.TokenHandler(strconv.FormatInt(login.Id, 10))
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    "500",
			Data:    nil,
		}, nil
	}

	return &types.Response{
		Message: "登录成功",
		Code:    "200",
		Data:    handler,
	}, nil
}
